import config from '@/config.js'
import { reactive } from 'vue'
import { t } from '@/locale/index'
import {requestHeader} from '@/common/util'

export default function useApi() {
  const state = reactive({
    loading: false,
    loaded: false,
    error: null
  })

  // 使用  uni.request 封装请求，返回 Promise，get post put delete
  const request = (url, method, data) => {
    let baseUrl = config.apiBaseUrl

    // #ifdef H5
    baseUrl = 'api/'
    // #endif

    state.loading = true;

    if (method !== 'GET') {
      uni.showLoading({ title: t('common.load_ing'), mask: true })
    }

    return new Promise((resolve, reject) => {
      uni.request({
        url: baseUrl + url,
        method: method,
        data: data,
        header: requestHeader(),
        success: (res) => {
          if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve(res.data);
          } else {
            reject(res.data);
          }

          if (res.statusCode == 401) {
            uni.removeStorageSync('account')
          }
        },
        fail: (err) => {
          reject(err);
        },
        complete: () => {
          state.loading = false;
          state.loaded = true;
          uni.hideLoading();
          uni.stopPullDownRefresh()
        }
      });
    });
  }

  const get = (url, data) => {
    return request(url, 'GET', data);
  }

  const post = (url, data) => {
    return request(url, 'POST', data);
  }

  const put = (url, data) => {
    return request(url, 'PUT', data);
  }

  const del = (url, data) => {
    return request(url, 'DELETE', data);
  }

  return {
    state,
    get,
    post,
    put,
    del
  }
}


